#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <sys/msg.h>

#include "aiot_state_api.h"
#include "aiot_sysdep_api.h"
#include "aiot_mqtt_api.h"
#include "aiot_dm_api.h"

int msgid;
union val_t {
    int b_val;
    int i_val;
    float f_val;
};
struct std_node
{
    int key;  //键值
    int type; //数据类型
    int dev_type;
    union val_t old_val;
    union val_t new_val;
    int ret;
};
struct msgbuf
{
    long type;
    int key;
    union val_t val;
} msg;
struct data
{
    int tfs;
    int d;
    int fm;
    int bjq;
    int jrp;
    int jsq;
    int fj;
} data;
int vale;
/* TODO: 替换为自己设备的三元组 */
const char *product_key = "k17yiBBhVOK";
const char *device_name = "XM001";
const char *device_secret = "63269411e761869dd798c426f9f2c5e8";
const char *mqtt_host = "iot-06z00c2mddkv6nb.mqtt.iothub.aliyuncs.com";
const uint16_t port = 8883;
extern aiot_sysdep_portfile_t g_aiot_sysdep_portfile;
extern const char *ali_ca_cert;
static pthread_t g_mqtt_process_thread;
static pthread_t g_mqtt_recv_thread;
static uint8_t g_mqtt_process_thread_running = 0;
static uint8_t g_mqtt_recv_thread_running = 0;

int32_t demo_state_logcb(int32_t code, char *message)
{
    // printf("%s", message);
    return 0;
}

void demo_mqtt_event_handler(void *handle, const aiot_mqtt_event_t *event, void *userdata)
{
    switch (event->type)
    {
    /* SDK因为用户调用了aiot_mqtt_connect()接口, 与mqtt服务器建立连接已成功 */
    case AIOT_MQTTEVT_CONNECT:
    {
        // printf("AIOT_MQTTEVT_CONNECT\n");
    }
    break;

    /* SDK因为网络状况被动断连后, 自动发起重连已成功 */
    case AIOT_MQTTEVT_RECONNECT:
    {
        //printf("AIOT_MQTTEVT_RECONNECT\n");
    }
    break;

    /* SDK因为网络的状况而被动断开了连接, network是底层读写失败, heartbeat是没有按预期得到服务端心跳应答 */
    case AIOT_MQTTEVT_DISCONNECT:
    {
        //char *cause = (event->data.disconnect == AIOT_MQTTDISCONNEVT_NETWORK_DISCONNECT) ? ("network disconnect") : ("heartbeat disconnect");
        // printf("AIOT_MQTTEVT_DISCONNECT: %s\n", cause);
    }
    break;

    default:
    {
    }
    }
}

/* 执行aiot_mqtt_process的线程, 包含心跳发送和QoS1消息重发 */
void *demo_mqtt_process_thread(void *args)
{
    int32_t res = STATE_SUCCESS;

    while (g_mqtt_process_thread_running)
    {
        res = aiot_mqtt_process(args);
        if (res == STATE_USER_INPUT_EXEC_DISABLED)
        {
            break;
        }
        sleep(1);
    }
    return NULL;
}

/* 执行aiot_mqtt_recv的线程, 包含网络自动重连和从服务器收取MQTT消息 */
void *demo_mqtt_recv_thread(void *args)
{
    int32_t res = STATE_SUCCESS;

    while (g_mqtt_recv_thread_running)
    {
        res = aiot_mqtt_recv(args);
        if (res < STATE_SUCCESS)
        {
            if (res == STATE_USER_INPUT_EXEC_DISABLED)
            {
                break;
            }
            sleep(1);
        }
    }
    return NULL;
}

static void demo_dm_recv_generic_reply(void *dm_handle, const aiot_dm_recv_t *recv, void *userdata)
{
}

static void demo_dm_recv_property_set(void *dm_handle, const aiot_dm_recv_t *recv, void *userdata)
{

    printf("demo_dm_recv_property_set msg_id = %ld, params = %.*s\r\n",
           (unsigned long)recv->data.property_set.msg_id,
           recv->data.property_set.params_len,
           recv->data.property_set.params);

    if (memcmp(recv->data.property_set.params, "{\"104\":", 7) == 0)
    {
        sscanf(recv->data.property_set.params, "{\"104\":%d}", &vale);
        msg.type = 10;
        msg.key = 104;
        msg.val.b_val = vale;

        msgsnd(msgid, &msg, sizeof(msg) - sizeof(long), 0);
        printf("msgsand:%ld:%d:%d\n", msg.type, msg.key, msg.val.b_val);
    }
    else if (memcmp(recv->data.property_set.params, "{\"105\":", 7) == 0)
    {
        sscanf(recv->data.property_set.params, "{\"105\":%d}", &vale);
        msg.type = 10;
        msg.key = 105;
        msg.val.b_val = vale;

        msgsnd(msgid, &msg, sizeof(msg) - sizeof(long), 0);
        printf("msgsand:%ld:%d:%d\n", msg.type, msg.key, msg.val.b_val);
    }
    else if (memcmp(recv->data.property_set.params, "{\"106\":", 7) == 0)
    {
        sscanf(recv->data.property_set.params, "{\"106\":%d}", &vale);
        msg.type = 10;
        msg.key = 106;
        msg.val.b_val = vale;

        msgsnd(msgid, &msg, sizeof(msg) - sizeof(long), 0);
        printf("msgsand:%ld:%d:%d\n", msg.type, msg.key, msg.val.b_val);
    }
    else if (memcmp(recv->data.property_set.params, "{\"107\":", 7) == 0)
    {
        sscanf(recv->data.property_set.params, "{\"107\":%d}", &vale);
        msg.type = 10;
        msg.key = 107;
        msg.val.b_val = vale;
        msgsnd(msgid, &msg, sizeof(msg) - sizeof(long), 0);
        printf("msgsand:%ld:%d:%d\n", msg.type, msg.key, msg.val.b_val);
    }
    else if (memcmp(recv->data.property_set.params, "{\"303\":", 7) == 0)
    {
        sscanf(recv->data.property_set.params, "{\"303\":%d}", &vale);
        msg.type = 20;
        msg.key = 303;
        msg.val.b_val = vale;
        msgsnd(msgid, &msg, sizeof(msg) - sizeof(long), 0);
        printf("msgsand:%ld:%d:%d\n", msg.type, msg.key, msg.val.b_val);
    }
    else if (memcmp(recv->data.property_set.params, "{\"304\":", 7) == 0)
    {
        sscanf(recv->data.property_set.params, "{\"304\":%d}", &vale);
        msg.type = 20;
        msg.key = 304;
        msg.val.b_val = vale;
        msgsnd(msgid, &msg, sizeof(msg) - sizeof(long), 0);
        printf("msgsand:%ld:%d:%d\n", msg.type, msg.key, msg.val.b_val);
    }
    else if (memcmp(recv->data.property_set.params, "{\"305\":", 7) == 0)
    {
        sscanf(recv->data.property_set.params, "{\"305\":%d}", &vale);
        msg.type = 20;
        msg.key = 305;
        msg.val.b_val = vale;
        msgsnd(msgid, &msg, sizeof(msg) - sizeof(long), 0);
        printf("msgsand:%ld:%d:%d\n", msg.type, msg.key, msg.val.b_val);
    }

    printf("**********************************************\n");
}

static void demo_dm_recv_async_service_invoke(void *dm_handle, const aiot_dm_recv_t *recv, void *userdata)
{
    // printf("demo_dm_recv_async_service_invoke msg_id = %ld, service_id = %s, params = %.*s\r\n",
    //        (unsigned long)recv->data.async_service_invoke.msg_id,
    //        recv->data.async_service_invoke.service_id,
    //        recv->data.async_service_invoke.params_len,
    //        recv->data.async_service_invoke.params);
}

static void demo_dm_recv_sync_service_invoke(void *dm_handle, const aiot_dm_recv_t *recv, void *userdata)
{
}

static void demo_dm_recv_raw_data(void *dm_handle, const aiot_dm_recv_t *recv, void *userdata)
{
    printf("demo_dm_recv_raw_data raw data len = %d\r\n", recv->data.raw_data.data_len);
}

static void demo_dm_recv_raw_sync_service_invoke(void *dm_handle, const aiot_dm_recv_t *recv, void *userdata)
{
    // printf("demo_dm_recv_raw_sync_service_invoke raw sync service rrpc_id = %s, data_len = %d\r\n",
    //        recv->data.raw_service_invoke.rrpc_id,
    //        recv->data.raw_service_invoke.data_len);
}

static void demo_dm_recv_raw_data_reply(void *dm_handle, const aiot_dm_recv_t *recv, void *userdata)
{
    // printf("demo_dm_recv_raw_data_reply receive reply for up_raw msg, data len = %d\r\n", recv->data.raw_data.data_len);
    /* TODO: 用户处理下行的二进制数据, 位于recv->data.raw_data.data中 */
}

/* 用户数据接收处理回调函数 */
static void demo_dm_recv_handler(void *dm_handle, const aiot_dm_recv_t *recv, void *userdata)
{
    // printf("demo_dm_recv_handler, type = %d\r\n", recv->type);

    switch (recv->type)
    {

    /* 属性上报, 事件上报, 获取期望属性值或者删除期望属性值的应答 */
    case AIOT_DMRECV_GENERIC_REPLY:
    {
        demo_dm_recv_generic_reply(dm_handle, recv, userdata);
    }
    break;

    /* 属性设置 */
    case AIOT_DMRECV_PROPERTY_SET:
    {
        demo_dm_recv_property_set(dm_handle, recv, userdata);
    }
    break;

    /* 异步服务调用 */
    case AIOT_DMRECV_ASYNC_SERVICE_INVOKE:
    {
        demo_dm_recv_async_service_invoke(dm_handle, recv, userdata);
    }
    break;

    /* 同步服务调用 */
    case AIOT_DMRECV_SYNC_SERVICE_INVOKE:
    {
        demo_dm_recv_sync_service_invoke(dm_handle, recv, userdata);
    }
    break;

    /* 下行二进制数据 */
    case AIOT_DMRECV_RAW_DATA:
    {
        demo_dm_recv_raw_data(dm_handle, recv, userdata);
    }
    break;

    /* 二进制格式的同步服务调用, 比单纯的二进制数据消息多了个rrpc_id */
    case AIOT_DMRECV_RAW_SYNC_SERVICE_INVOKE:
    {
        demo_dm_recv_raw_sync_service_invoke(dm_handle, recv, userdata);
    }
    break;

    /* 上行二进制数据后, 云端的回复报文 */
    case AIOT_DMRECV_RAW_DATA_REPLY:
    {
        demo_dm_recv_raw_data_reply(dm_handle, recv, userdata);
    }
    break;

    default:
        break;
    }
}

/* 属性上报函数演示 */
int32_t demo_send_property_post(void *dm_handle, char *params)
{
    aiot_dm_msg_t msg;

    memset(&msg, 0, sizeof(aiot_dm_msg_t));
    msg.type = AIOT_DMMSG_PROPERTY_POST;
    msg.data.property_post.params = params;

    return aiot_dm_send(dm_handle, &msg);
}

int32_t demo_send_property_batch_post(void *dm_handle, char *params)
{
    aiot_dm_msg_t msg;

    memset(&msg, 0, sizeof(aiot_dm_msg_t));
    msg.type = AIOT_DMMSG_PROPERTY_BATCH_POST;
    msg.data.property_post.params = params;

    return aiot_dm_send(dm_handle, &msg);
}

/* 事件上报函数演示 */
int32_t demo_send_event_post(void *dm_handle, char *event_id, char *params)
{
    aiot_dm_msg_t msg;

    memset(&msg, 0, sizeof(aiot_dm_msg_t));
    msg.type = AIOT_DMMSG_EVENT_POST;
    msg.data.event_post.event_id = event_id;
    msg.data.event_post.params = params;

    return aiot_dm_send(dm_handle, &msg);
}

/* 演示了获取属性LightSwitch的期望值, 用户可将此函数加入到main函数中运行演示 */
int32_t demo_send_get_desred_requset(void *dm_handle)
{
    aiot_dm_msg_t msg;

    memset(&msg, 0, sizeof(aiot_dm_msg_t));
    msg.type = AIOT_DMMSG_GET_DESIRED;
    msg.data.get_desired.params = "[\"LightSwitch\"]";

    return aiot_dm_send(dm_handle, &msg);
}

/* 演示了删除属性LightSwitch的期望值, 用户可将此函数加入到main函数中运行演示 */
int32_t demo_send_delete_desred_requset(void *dm_handle)
{
    aiot_dm_msg_t msg;

    memset(&msg, 0, sizeof(aiot_dm_msg_t));
    msg.type = AIOT_DMMSG_DELETE_DESIRED;
    msg.data.get_desired.params = "{\"LightSwitch\":{}}";

    return aiot_dm_send(dm_handle, &msg);
}

int main(int argc, char *argv[])
{
    int32_t res = STATE_SUCCESS;
    void *dm_handle = NULL;
    void *mqtt_handle = NULL;
    aiot_sysdep_network_cred_t cred; /* 安全凭据结构体, 如果要用TLS, 这个结构体中配置CA证书等参数 */
    uint8_t post_reply = 1;

    /* 配置SDK的底层依赖 */
    aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile);
    /* 配置SDK的日志输出 */
    aiot_state_set_logcb(demo_state_logcb);

    /* 创建SDK的安全凭据, 用于建立TLS连接 */
    memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t));
    cred.option = AIOT_SYSDEP_NETWORK_CRED_SVRCERT_CA; /* 使用RSA证书校验MQTT服务端 */
    cred.max_tls_fragment = 16384;                     /* 最大的分片长度为16K, 其它可选值还有4K, 2K, 1K, 0.5K */
    cred.sni_enabled = 1;                              /* TLS建连时, 支持Server Name Indicator */
    cred.x509_server_cert = ali_ca_cert;               /* 用来验证MQTT服务端的RSA根证书 */
    cred.x509_server_cert_len = strlen(ali_ca_cert);   /* 用来验证MQTT服务端的RSA根证书长度 */

    /* 创建1个MQTT客户端实例并内部初始化默认参数 */
    mqtt_handle = aiot_mqtt_init();
    if (mqtt_handle == NULL)
    {
        printf("aiot_mqtt_init failed\n");
        return -1;
    }

    /* 配置MQTT服务器地址 */
    aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_HOST, (void *)mqtt_host);
    /* 配置MQTT服务器端口 */
    aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PORT, (void *)&port);
    /* 配置设备productKey */
    aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PRODUCT_KEY, (void *)product_key);
    /* 配置设备deviceName */
    aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_NAME, (void *)device_name);
    /* 配置设备deviceSecret */
    aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_SECRET, (void *)device_secret);
    /* 配置网络连接的安全凭据, 上面已经创建好了 */
    aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_NETWORK_CRED, (void *)&cred);
    /* 配置MQTT事件回调函数 */
    aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_EVENT_HANDLER, (void *)demo_mqtt_event_handler);

    /* 创建DATA-MODEL实例 */
    dm_handle = aiot_dm_init();
    if (dm_handle == NULL)
    {
        printf("aiot_dm_init failed");
        return -1;
    }
    /* 配置MQTT实例句柄 */
    aiot_dm_setopt(dm_handle, AIOT_DMOPT_MQTT_HANDLE, mqtt_handle);
    /* 配置消息接收处理回调函数 */
    aiot_dm_setopt(dm_handle, AIOT_DMOPT_RECV_HANDLER, (void *)demo_dm_recv_handler);

    /* 配置是云端否需要回复post_reply给设备. 如果为1, 表示需要云端回复, 否则表示不回复 */
    aiot_dm_setopt(dm_handle, AIOT_DMOPT_POST_REPLY, (void *)&post_reply);

    /* 与服务器建立MQTT连接 */
    res = aiot_mqtt_connect(mqtt_handle);
    if (res < STATE_SUCCESS)
    {
        /* 尝试建立连接失败, 销毁MQTT实例, 回收资源 */
        aiot_dm_deinit(&dm_handle);
        aiot_mqtt_deinit(&mqtt_handle);
        printf("aiot_mqtt_connect failed: -0x%04X\n\r\n", -res);
        printf("please check variables like mqtt_host, produt_key, device_name, device_secret in demo\r\n");
        return -1;
    }

    /* 向服务器订阅property/batch/post_reply这个topic */

    char *sub_topic = "/sys/k17yiBBhVOK/XM001/thing/service/property/set";
    res = aiot_mqtt_sub(mqtt_handle, sub_topic, NULL, 1, NULL);
    if (res < 0)
    {
        printf("aiot_mqtt_sub failed, res: -0x%04X\n", -res);
        return -1;
    }

    /* 创建一个单独的线程, 专用于执行aiot_mqtt_process, 它会自动发送心跳保活, 以及重发QoS1的未应答报文 */
    g_mqtt_process_thread_running = 1;
    res = pthread_create(&g_mqtt_process_thread, NULL, demo_mqtt_process_thread, mqtt_handle);
    if (res < 0)
    {
        printf("pthread_create demo_mqtt_process_thread failed: %d\n", res);
        aiot_dm_deinit(&dm_handle);
        aiot_mqtt_deinit(&mqtt_handle);
        return -1;
    }

    /* 创建一个单独的线程用于执行aiot_mqtt_recv, 它会循环收取服务器下发的MQTT消息, 并在断线时自动重连 */
    g_mqtt_recv_thread_running = 1;
    res = pthread_create(&g_mqtt_recv_thread, NULL, demo_mqtt_recv_thread, mqtt_handle);
    if (res < 0)
    {
        printf("pthread_create demo_mqtt_recv_thread failed: %d\n", res);
        aiot_dm_deinit(&dm_handle);
        aiot_mqtt_deinit(&mqtt_handle);
        return -1;
    }
    key_t key, key_msg;
    int shmid;
    int *n = NULL;
    struct std_node *stu = NULL;
    key = ftok("/mnt/shm.txt", 'j');
    if (key < 0)
    {
        perror("ftok err");
        return -1;
    }
    printf("key: %#x\n", key);

    //打开或创建共享内存
    shmid = shmget(key, sizeof(stu), IPC_CREAT | IPC_EXCL | 0666); //创建共享内存
    if (shmid <= 0)
    {
        if (errno == EEXIST)
            shmid = shmget(key, sizeof(stu), 0666); //直接打开已经存在的共享内存
        else
        {
            perror("shmget err");
            return -1;
        }
    }
    printf("shmid: %d\n", shmid);

    //映射共享内存
    n = (int *)shmat(shmid, NULL, 0);
    if (n == (int *)-1)
    {
        perror("shmat err");
        return -1;
    }
    int a = *n;
    stu = (struct std_node *)(n + 1);
    char buf[32] = "";

    key_msg = ftok("/mnt/msg.txt", 'b');
    if (key_msg < 0)
    {
        perror("ftok err_msg");
    }
    printf("key1:%#x\n", key_msg);

    //打开消息队列
    msgid = msgget(key_msg, IPC_CREAT | IPC_EXCL | 0666);
    if (msgid <= 0)
    {
        if (errno == EEXIST)
            msgid = msgget(key_msg, 0666);
        else
        {
            perror("msgget err");
        }
    }
    /* 主循环进入休眠 */
    while (1)
    {
        for (int i = 0; i < a; i++)
        {
            memset(buf, 0, 32);
            switch (stu->key)
            {
            case 301:
                sprintf(buf, "{\"301\": %d}", stu->new_val.i_val);
                demo_send_property_post(dm_handle, buf);
                break;
            case 302:
                sprintf(buf, "{\"302\": %d}", stu->new_val.i_val);
                demo_send_property_post(dm_handle, buf);
                break;
            case 303:
                sprintf(buf, "{\"303\": %d}", stu->new_val.b_val);
                demo_send_property_post(dm_handle, buf);
                data.jsq = stu->new_val.b_val;
                break;
            case 304:
                sprintf(buf, "{\"304\": %d}", stu->new_val.b_val);
                demo_send_property_post(dm_handle, buf);
                data.jrp = stu->new_val.b_val;
                break;
            case 305:
                sprintf(buf, "{\"305\": %d}", stu->new_val.b_val);
                demo_send_property_post(dm_handle, buf);
                data.fj = stu->new_val.b_val;
                break;
            case 101:
                sprintf(buf, "{\"101\": %d}", stu->new_val.i_val);
                demo_send_property_post(dm_handle, buf);
                break;
            case 102:
                sprintf(buf, "{\"102\": %.2f}", stu->new_val.f_val);
                demo_send_property_post(dm_handle, buf);
                break;
            case 103:
                sprintf(buf, "{\"103\": %.2f}", stu->new_val.f_val);
                demo_send_property_post(dm_handle, buf);
                break;
            case 104:
                sprintf(buf, "{\"104\": %d}", stu->new_val.b_val);
                demo_send_property_post(dm_handle, buf);
                data.tfs = stu->new_val.b_val;
                break;
            case 105:
                sprintf(buf, "{\"105\": %d}", stu->new_val.b_val);
                demo_send_property_post(dm_handle, buf);
                data.d = stu->new_val.b_val;
                break;
            case 106:
                sprintf(buf, "{\"106\": %d}", stu->new_val.b_val);
                demo_send_property_post(dm_handle, buf);
                data.fm = stu->new_val.b_val;
                break;
            case 107:
                sprintf(buf, "{\"107\": %d}", stu->new_val.b_val);
                demo_send_property_post(dm_handle, buf);
                data.bjq = stu->new_val.b_val;
                break;

            default:
                break;
            }
            //printf("%s\n", buf);
            stu++;
        }
        stu = (struct std_node *)(n + 1);

        sleep(3);
    }

    /* 停止收发动作 */
    g_mqtt_process_thread_running = 0;
    g_mqtt_recv_thread_running = 0;
    shmdt(n);

    /* 断开MQTT连接, 一般不会运行到这里 */
    res = aiot_mqtt_disconnect(mqtt_handle);
    if (res < STATE_SUCCESS)
    {
        aiot_dm_deinit(&dm_handle);
        aiot_mqtt_deinit(&mqtt_handle);
        printf("aiot_mqtt_disconnect failed: -0x%04X\n", -res);
        return -1;
    }

    /* 销毁DATA-MODEL实例, 一般不会运行到这里 */
    res = aiot_dm_deinit(&dm_handle);
    if (res < STATE_SUCCESS)
    {
        printf("aiot_dm_deinit failed: -0x%04X\n", -res);
        return -1;
    }

    /* 销毁MQTT实例, 一般不会运行到这里 */
    res = aiot_mqtt_deinit(&mqtt_handle);
    if (res < STATE_SUCCESS)
    {
        printf("aiot_mqtt_deinit failed: -0x%04X\n", -res);
        return -1;
    }

    pthread_join(g_mqtt_process_thread, NULL);
    pthread_join(g_mqtt_recv_thread, NULL);

    return 0;
}
